package com.lyx.userserver.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lyx.common.entity.User;
import com.lyx.common.utils.JwtUtils;
import com.lyx.userserver.user.dao.UserMapper;
import com.lyx.userserver.user.param.LoginParam;
import com.lyx.userserver.user.service.UserService;
import com.lyx.userserver.user.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public String login(LoginParam loginParam) {
        // 判断用户名和密码
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, loginParam.getUsername()));
        if (user == null) {
            throw new RuntimeException("用户名不存在");
        }
        if (!user.getPassword().equals(loginParam.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 验证成功，返回token(jwt)
        Map<String, Object> claims = new HashMap<>();
        claims.put("uid", user.getId());
        String jwt = JwtUtils.createJwt(claims);

        return jwt;
    }

    @Override
    public UserVO my(Integer uid) {
        User user = userMapper.selectById(uid);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);

        //签到状态
        userVO.setSignFlag(0);
        return userVO;
    }
}
